package com.alawn.web.security.controller;

import java.util.List;

import org.ocpsoft.rewrite.annotation.Join;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.alawn.framework.core.web.faces.annotation.MessageRequired;
import com.alawn.framework.core.web.faces.annotation.MessageType;
import com.alawn.framework.core.web.faces.controller.FacesController;
import com.alawn.framework.services.security.Role;
import com.alawn.security.service.ResourceService;
import com.alawn.security.service.RoleService;

@Controller("/views/security/role.faces")
@Join(path = "/security/role", to = "/views/security/role.faces")
public class RoleController extends FacesController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    @Override
    public void initPage() {
        putViewScope("resources", resourceService.treeDataModel(null));
        dataList(null);
    }


    public void dataList(Role role) {
        List<Role> roles = roleService.list();
        roles.add(0, new Role());
        putViewScope("roles", roles);
        putViewScope("selectedRole", role);
    }

    public void add() {
        Role role = new Role();
        putViewScope("role", role);
    }

    @MessageRequired(type = MessageType.SAVE)
    public void save() {
        Role role = (Role) getViewScope("role");
        roleService.save(role);
        dataList(role);
    }

    public void onSelectRow() {
        Role role = (Role) getViewScope("selectedRole");
        if (role.getId() != null) {
            role = roleService.getById(role.getId());
        }
        putViewScope("role", role);
    }

    public void edit() {
        Role role = (Role) getViewScope("selectedRole");
        role = roleService.getById(role.getId());
        putViewScope("role", role);
    }

    @MessageRequired(type = MessageType.DELETE)
    public void delete() {
        Role role = (Role) getViewScope("selectedRole");
        roleService.removeById(role);
        dataList(null);
    }
}
